import json
import httpx

from loguru import logger


class DingBot:
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token='

    def __init__(self, access_token):
        self.webhook = 'https://oapi.dingtalk.com/robot/send?access_token=' + access_token

    async def send_text(self, msg):
        url = self.webhook
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "text",
            "text": {
                "content": msg
            }
        }
        async with httpx.AsyncClient() as client:
            response = await client.post(url, headers=headers, data=json.dumps(data))

        if response.status_code == 200:
            logger.info('DingBot send success')
            logger.info(response.text)

        return response.json()

    async def send_markdown(self, msg):
        url = self.webhook
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": "通知",
                "text": msg
            }
        }
        async with httpx.AsyncClient() as client:
            response = await client.post(url, headers=headers, data=json.dumps(data))

        if response.status_code == 200:
            logger.info('DingBot send success')
            logger.info(response.text)

        return response.json()


__all__ = [
    'DingBot'
]
